package com.chinapost.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.chinapost.excelUtil.ExcelUtils;
import com.chinapost.excelUtil.JsGridReportBase;
import com.chinapost.excelUtil.TableData;
import com.chinapost.service.DeptServiceI;
import com.chinapost.service.UserServiceI;
import com.chinapost.util.IpUtil;
import com.chinapost.util.ResourceUtil;
import com.chinapost.vo.Json;
import com.chinapost.vo.SessionInfo;
import com.chinapost.vo.User;
import com.opensymphony.xwork2.ModelDriven;

@Namespace("/")
@Action(value = "userAction", results = { @Result(name = "userManager", location = "/jsp/user/manager.jsp"), 
		@Result(name = "userAdd", location = "/jsp/user/userAdd.jsp"),
		@Result(name = "add", location = "/jsp/user/add.jsp"),
		@Result(name = "userEdit", location = "/jsp/user/userEdit.jsp"),
		@Result(name = "edit", location = "/jsp/user/edit.jsp"),
		@Result(name = "userImport", location = "/jsp/user/userImport.jsp"),
		@Result(name = "changePwd", location = "/jsp/user/changePwd.jsp") })
public class UserAction extends BaseAction implements ModelDriven<User>, ServletRequestAware,ServletResponseAware {

	private UserServiceI userService;
	private DeptServiceI deptService;
	private User user = new User();
	private HttpServletRequest request;
	private HttpServletResponse response;

	public DeptServiceI getDeptService() {
		return deptService;
	}

	@Autowired
	public void setDeptService(DeptServiceI deptService) {
		this.deptService = deptService;
	}

	public UserServiceI getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserServiceI userService) {
		this.userService = userService;
	}

	@Override
	public User getModel() {
		return user;
	}

	public String userManager() {
		return "userManager";
	}

	public String userAdd() {
		SessionInfo si=(SessionInfo)ServletActionContext.getRequest().getSession().getAttribute("sessionInfo");
		if (si.getLoginName().equals("admin")){
			return "userAdd";
		}else{
			return "add";
		}
	}

	public String userEdit() {
		SessionInfo si=(SessionInfo)ServletActionContext.getRequest().getSession().getAttribute("sessionInfo");
		if (si.getLoginName().equals("admin")){
			return "userEdit";
		}else{
			return "edit";
		}
	}

	public String userImport() {
		return "userImport";
	}
	
	public String doNotNeedAuth_userChangePwd() {
		return "changePwd";
	}

	public void edit() {
		Json j = new Json();
		try {
			userService.edit(user);
			j.setSuccess(true);
			j.setMsg("编辑成功！");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("编辑失败！");
		}
		super.writeJson(j);
	}

	public void delete() {
		Json j = new Json();
		try {
			userService.delete(user);
			j.setSuccess(true);
			j.setMsg("删除用户成功！");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("删除失败！");
		}
		super.writeJson(j);
	}

	public void add() {
		Json j = new Json();
		try {
			userService.add(user);
			j.setMsg("添加成功！");
			j.setSuccess(true);
		} catch (Exception e) {
			j.setMsg("添加失败！");
			j.setSuccess(false);
		}
		super.writeJson(j);
	}
	
	public void addUsers() {
		Json j = new Json();
		int count = 0;
		try {
			count = userService.addUsers(user);
			if (count > 0) {
				j.setSuccess(true);
				j.setMsg("上传成功，新增" + count + "条记录！");
			} else {
				j.setMsg("上传失败,新增0条记录！");
			}
		} catch (Exception e) {
			j.setMsg("上传失败,新增0条记录！");
		}
		super.writeJson(j);
	}

	public void datagrid() {
		if (!StringUtils.isEmpty(user.getDeptid())) {
			user.setDeptIds(deptService.getChildIds(user.getDeptid()));
		} else {
			SessionInfo s = (SessionInfo)request.getSession().getAttribute("sessionInfo");
			user.setDeptIds(deptService.getChildIds(s.getDeptid()));
		}
		super.writeJsonDate(userService.datagrid(user));
	}

	public void do_combobox(){
		List<User> users = new ArrayList<User>();
		if (!StringUtils.isEmpty(user.getDeptid())){
			users=userService.listUserByDeptid(user.getDeptid());
		}
		super.writeJson(users);
	}
	
	public void do_login() {
		Json j = new Json();
		String yzm = (String) request.getSession().getAttribute("yzm");
		if (yzm != null && yzm.equalsIgnoreCase(user.getVerifyCode())) {
			User u = userService.login(user);
			if (u.isSuccess()) {
				SessionInfo sessionInfo = new SessionInfo();
				sessionInfo.setUserId(u.getCid());
				sessionInfo.setLoginName(u.getCname());
				sessionInfo.setBh(u.getCbh());
				sessionInfo.setRoleIds(u.getRoleIds());
				sessionInfo.setRoleNames(u.getRoleNames());
				sessionInfo.setDeptid(u.getDeptid());
				sessionInfo.setDeptName(u.getDeptname());
				sessionInfo.setResourceUrls(u.getResourceUrls());
				sessionInfo.setIpAddress(IpUtil.getIpAddr(ServletActionContext.getRequest()));
				request.getSession().setAttribute(ResourceUtil.getSessionInfoName(), sessionInfo);
				j.setSuccess(true);
				j.setObj(u);
				j.setMsg("登陆成功！");
			} else {
				j.setSuccess(false);
				j.setCount(u.getError());
				j.setMsg("登陆失败，用户名或密码错误，请联系系统管理员！");
			}
		} else {
			j.setSuccess(false);
			j.setCount(4);// 验证码错误代码
			j.setMsg("验证码错误，请输入正确验证码！");
		}
		super.writeJson(j);
	}

	public void doNotNeedAuth_ChangePwd() {
		Json j = new Json();
		try {
			boolean b = userService.changePwd(user);
			if (b) {
				j.setMsg("密码修改成功！");
				j.setSuccess(true);
			} else {
				j.setMsg("密码修改失败！");
				j.setSuccess(false);
			}
		} catch (Exception e) {
			j.setMsg("密码修改失败！");
			j.setSuccess(false);
		}
		super.writeJson(j);
	}

	public void do_logout() {
		request.getSession().invalidate();
		Json j = new Json();
		j.setSuccess(true);
		super.writeJson(j);
	}

	public void changeStatus() {
		Json j = new Json();
		try {
			userService.changeStatus(user);
			j.setSuccess(true);
			j.setMsg("更改用户状态成功！");
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("更改用户状态失败！");
		}
		super.writeJson(j);
	}

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;

	}
	
	public void exportExcel() throws Exception {
		response.setContentType("application/msexcel;charset=GBK");
		SessionInfo s = (SessionInfo) request.getSession().getAttribute("sessionInfo");
		if (!StringUtils.isEmpty(user.getDeptid())) {
			user.setDeptIds(deptService.getAllChildids(user.getDeptid()));
		} else {
			user.setDeptIds(deptService.getAllChildids(s.getDeptid()));
		}
		List<User> list = new ArrayList<User>();
		list = userService.excelData(user);
		String title = "";
		if (!StringUtils.isEmpty(user.getDeptid())){
			title = deptService.getNameById(user.getDeptid());
		}else{
			title = s.getDeptName();
		}
		title += "人员信息表";
		String[] hearders = new String[] { "部门", "编号","姓名", "人员类别" };// 表头数组
		String[] fields = new String[] { "deptname","cbh","cname", "yglbname"};// 对象属性数组
		int[] columnwidths = new int[] { 22, 18, 20,20};
		TableData td = ExcelUtils.createTableData(list, ExcelUtils.createTableHeader(hearders), fields);
		JsGridReportBase report = new JsGridReportBase(request, response);
		report.exportToExcel(title, "admin", columnwidths, td);
	}

	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	
}
